package com.stars.easyms.base.util;

import com.stars.easyms.base.bean.EasyMsResponseEntity;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * <p>className: EasyMsResponseEntityUtil</p>
 * <p>description: EasyMsResponseEntity工具类</p>
 *
 * @author guoguifang
 * @version 1.7.3
 * @date 2021/3/20 3:55 下午
 */
public final class EasyMsResponseEntityUtil {

    private static final Map<Type, Boolean> EASY_MS_RESPONSE_ENTITY_TYPE_CACHE = new ConcurrentHashMap<>(32);

    /**
     * 判断是否是EasyMsResponseEntityType类型或类EasyMsResponseEntityType结构类型
     *
     * @param type 类型
     */
    public static boolean isEasyMsResponseEntityType(Type type) {
        return EASY_MS_RESPONSE_ENTITY_TYPE_CACHE.computeIfAbsent(type, t -> {
            Type rawType = t;
            if (t instanceof ParameterizedType) {
                rawType = ((ParameterizedType) t).getRawType();
            }
            if (EasyMsResponseEntity.class.equals(rawType)) {
                return true;
            }
            try {
                Class<?> rawClass = (Class<?>) rawType;
                rawClass.getDeclaredMethod("setRetCode", String.class);
                rawClass.getDeclaredMethod("setRetMsg", String.class);
                rawClass.getDeclaredMethod("setErrorDesc", String.class);
                rawClass.getDeclaredMethod("setBody", Object.class);
            } catch (NoSuchMethodException e) {
                return false;
            }
            return true;
        });
    }

    public static EasyMsParameterizedType getEasyMsResponseEntityParameterizedType(Type type) {
        return new EasyMsParameterizedType(new Type[]{type}, null, EasyMsResponseEntity.class);
    }

    private EasyMsResponseEntityUtil() {
    }
}
